package com.dr.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dr.entity.User;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		//获取请求的RUi:去除http:localhost:8080这部分剩下的
		 String url = request.getRequestURI();
		 //UTL:除了login.jsp是可以公开访问的，其他的URL都进行拦截控制
		 if (url.indexOf("/index/findLogin.do") >= 0 
				 || url.indexOf("/index/insertIndexUser.do") >= 0
				 || url.indexOf("/index/getVerifiCode.do") >= 0
				 || url.indexOf("/index/index.do") >= 0
				 || url.indexOf("/index/*") >= 0) {
		 return true;
		 }
		 //获取session
		 HttpSession session = request.getSession();
		 User user1 = (User) session.getAttribute("loginUser");
		 //判断session中是否有用户数据，如果有，则返回true，继续向下执行
		 if (user1 != null) {
		 //return true代表放行
		 return true;
		 }
		 //不符合条件的给出提示信息，并转发到登录页面
		 request.setAttribute("msg", "您还没有登录，请先登录！");
		 request.getRequestDispatcher("/index/login.jsp").forward(request, response);
		 //return false代表拦截
		 return false;
	}

}
